import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'api_service.dart';

class AuthService {
  static const String _tokenKey = 'auth_token';

  /// 登录
  static Future<String> login(String username, String password) async {
    final url = '${ApiService.baseUrl}/user/login';

    print('🔐 Login Request: POST $url');
    print('📦 Request Body: username=$username');

    try {
      final response = await http.post(
        Uri.parse(url),
        headers: {
          'Content-Type': 'application/json',
        },
        body: json.encode({
          'username': username,
          'password': password,
        }),
      );

      final responseBody = utf8.decode(response.bodyBytes);
      print('✅ Login Response: ${response.statusCode}');
      print('📥 Response Body: $responseBody');

      if (response.statusCode == 200) {
        final jsonData = json.decode(responseBody);

        if (jsonData['code'] == 200) {
          final token = jsonData['data']['token'] as String;
          await saveToken(token);
          return token;
        } else {
          throw Exception(jsonData['message'] ?? '登录失败');
        }
      } else {
        throw Exception('请求失败: ${response.statusCode}');
      }
    } catch (e) {
      print('❌ Login Error: $e');
      throw Exception('登录异常: $e');
    }
  }

  /// 保存 token
  static Future<void> saveToken(String token) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_tokenKey, token);
    print('💾 Token saved successfully');
  }

  /// 获取 token
  static Future<String?> getToken() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(_tokenKey);
  }

  /// 清除 token
  static Future<void> clearToken() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_tokenKey);
    print('🗑️ Token cleared');
  }

  /// 检查是否已登录
  static Future<bool> isLoggedIn() async {
    final token = await getToken();
    return token != null && token.isNotEmpty;
  }
}
